package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.entity.dto.employee.AddEmployeeDto;
import com.itheima.entity.dto.employee.EmployeeLoginDto;
import com.itheima.entity.dto.employee.EmployeeUpDto;
import com.itheima.entity.vo.employee.EmployeeIdVo;
import com.itheima.entity.vo.employee.EmployeeLoginVo;
import com.itheima.entity.vo.employee.EmployeePageVo;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author huangzelnag
 * @create 2022-05-09
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;


    @PostMapping("login")
    public R Login(@RequestBody EmployeeLoginDto employeeLoginDto){
        EmployeeLoginVo employeeLogin = employeeService.getEmployeeLogin(employeeLoginDto);

        if(employeeLogin==null){

            return R.error("用户名或密码错误");
        }

        return R.success(employeeLogin);
    }

    @PostMapping("logout")
    public R logout(HttpServletRequest req){
        String token = req.getHeader("Authorization");
        employeeService.logout(token);
        return R.success("登出");
    }


    /**
     * 分页查询列表
     * @param name
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("page")
    public R getPage(@RequestParam(required = false) String name,
                     @RequestParam(required = false) Integer page,
                     @RequestParam(required = false) Integer pageSize ){

        EmployeePageVo employeePage = employeeService.getEmployeePage(name, page, pageSize);


        if(employeePage==null){
            return R.error("获取到的列表为空");
        }


        return R.success(employeePage);


    }


    /**
     * 添加员工
     * @param addEmployeeDto
     * @return
     */
    @PostMapping("")
    public R addEmployee(@RequestBody AddEmployeeDto addEmployeeDto){
        Boolean aBoolean = employeeService.addEmployee(addEmployeeDto);

        if(aBoolean){
            return R.success("成功");

        }else {
            String msg = "'"+addEmployeeDto.getUsername()+"'"+"已存在";
            return R.error(msg);
        }



    }


    @GetMapping("{id}")
    public R getEmployeeId(@PathVariable String id){
        EmployeeIdVo employeeById = employeeService.getEmployeeById(id);

        if(Objects.nonNull(employeeById)){
            return R.success(employeeById);
        }
        else {
            return R.error("查不到对应id");
        }

    }

    @PutMapping
    public R updateEmployee(@RequestBody EmployeeUpDto employeeUpDto){

        boolean b = employeeService.updateEmployee(employeeUpDto);

        if(b){
            return R.success("员工信息修改成功");
        }else {
            return R.error("修改失败");
        }
    }




}
